from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """
    购物车序列化器
    """
    sku_id = serializers.IntegerField(label='sku id ', min_value=1)
    count = serializers.IntegerField(label='数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选', default=True)


    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError("sku_id不存在")
            # 判断库存
        if attrs['count'] >sku.stock:
            raise serializers.ValidationError('库存不足')

        return attrs



class CartSKUSerializer(serializers.ModelSerializer):
    count = serializers.IntegerField(read_only=True)
    selected = serializers.BooleanField(read_only=True)

    class Meta:
        model = SKU
        fields = '__all__'


class CartDeleteSerializer(serializers.Serializer):
    """
    购物车序列化器
    """
    sku_id = serializers.IntegerField(label='sku id ', min_value=1)

    def validate(self, attrs):
        try:
            sku = SKU.objects.filter(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError("sku_id不存在")
        return attrs

class CartSelectedSerializers(serializers.Serializer):
    selected = serializers.BooleanField()